//
//  GBNSUtils.m
//  PngOK
//
//  Created by wanglidong on 14-4-30.
//  Copyright (c) 2014年 GoldenBull. All rights reserved.
//

#import "GBNSUtils.h"

@implementation GBNSUtils

+ (void)addTarget:(id)target action:(SEL)action forControl:(id)control
{
    [control setTarget:target];
    [control setAction:action];
}


+ (NSString *)runCommand:(NSString *)command2Run
{
    NSTask *task;
    task = [[NSTask alloc] init];
    [task setLaunchPath: @"/bin/sh"];
    
    NSArray *arguments = [NSArray arrayWithObjects:
                          @"-c" ,
                          [NSString stringWithFormat:@"%@", command2Run],
                          nil];
    //NSLog(@"run command: %@",commandToRun);
    [task setArguments: arguments];
    
    NSPipe *pipe;
    pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];
    
    NSFileHandle *file;
    file = [pipe fileHandleForReading];
    
    [task launch];
    
    NSData *data;
    data = [file readDataToEndOfFile];
    
    NSString *output;
    output = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
    return output;
}

+ (void)openFolder:(BOOL)canCreateDirectories completionHandler:(void (^)(NSInteger result, NSString *path))handler
{
    NSOpenPanel *oPanel = [NSOpenPanel openPanel];
    [oPanel setCanChooseDirectories:YES];
    [oPanel setCanChooseFiles:NO];
    [oPanel setCanCreateDirectories:canCreateDirectories];
    [oPanel beginWithCompletionHandler:^(NSInteger result) {
        
        if (1 == result)
        {
            handler(result, [[oPanel URL] relativePath]);
        }
        else
        {
            handler(result, @"");
        }
    }];
}

+ (void)openItem:(NSArray *)filters completionHandler:(void (^)(NSInteger result, NSArray *urls))handler
{
    NSOpenPanel *oPanel = [NSOpenPanel openPanel];
    [oPanel setCanChooseDirectories:YES];
    [oPanel setCanChooseFiles:YES];
    [oPanel setCanCreateDirectories:NO];
    [oPanel setAllowsMultipleSelection:YES];
    [oPanel setAllowedFileTypes:filters];
    
    [oPanel beginWithCompletionHandler:^(NSInteger result) {
        
        
        
        if (1 == result)
        {
            handler(result, [oPanel URLs]);
        }
        
    }];
}

@end
